﻿using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using TConvert = System.Convert;
using System.Collections;
using System.Text.RegularExpressions;

namespace DBA.Common
{
    public class AES:DEncryptBase
    {

        
        //默认密钥向量
        private byte[] Keys = { 0x41, 0x72, 0x65, 0x79, 0x6F, 0x75, 0x6D, 0x79, 0x53, 0x6E, 0x6F, 0x77, 0x6D, 0x61, 0x6E, 0x3F };

        public string Encode(string encryptString, string encryptKey)
        {
            encryptKey = StringHelper.GetSubString(encryptKey, 32, "");
            encryptKey = encryptKey.PadRight(32, ' ');

            RijndaelManaged rijndaelProvider = new RijndaelManaged();
            rijndaelProvider.Key = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 32));
            rijndaelProvider.IV = Keys;
            ICryptoTransform rijndaelEncrypt = rijndaelProvider.CreateEncryptor();

            byte[] inputData = Encoding.UTF8.GetBytes(encryptString);
            byte[] encryptedData = rijndaelEncrypt.TransformFinalBlock(inputData, 0, inputData.Length);

            return TConvert.ToBase64String(encryptedData);
        }

        public string Decode(string decryptString, string decryptKey)
        {
            try
            {
                decryptKey = StringHelper.GetSubString(decryptKey, 32, "");
                decryptKey = decryptKey.PadRight(32, ' ');

                RijndaelManaged rijndaelProvider = new RijndaelManaged();
                rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey);
                rijndaelProvider.IV = Keys;
                ICryptoTransform rijndaelDecrypt = rijndaelProvider.CreateDecryptor();

                byte[] inputData = TConvert.FromBase64String(decryptString);
                byte[] decryptedData = rijndaelDecrypt.TransformFinalBlock(inputData, 0, inputData.Length);

                return Encoding.UTF8.GetString(decryptedData);
            }
            catch
            {
                return "";
            }

        }

        public override string Encode(string encryptString)
        {
            string encryptKey = "LEGOFHERO";
            if (!VerificationHelper.IsNullOrEmpty<string>(Key))
            {
                encryptKey = Key;
            }
            return Encode(encryptString, encryptKey);
        }

        public override string Decode(string decryptString)
        {
            string decryptKey = "LEGOFHERO";
            if (!VerificationHelper.IsNullOrEmpty<string>(Key))
            {
                decryptKey = Key;
            }
            return Decode(decryptString, decryptKey);
        }
    }
}
